package com.idrl.web.action;

import java.io.*;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpSession;

import org.apache.commons.lang.RandomStringUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.time.DateFormatUtils;
import org.apache.log4j.Logger;
import org.directwebremoting.WebContextFactory;

import com.idrl.Const;
import com.idrl.MessageCode;
import com.idrl.dao.po.*;
import com.idrl.utils.RegexUtils;
import com.idrl.utils.SysConfig;

public class RegAction extends BaseAction {

	private static Logger log = Logger.getLogger(RegAction.class);	
	
	private User user;
	
	/** 邮箱激活ID */
	private int uid;
	
	/** 邮箱激活KEY */
	private String key;
	

	/**
	 * 转向注册页面。
	 * @return
	 */
	public String gotoReg()
	{
		return INPUT;
	}
	
	/**
	 * 注册
	 */
	public String execute()
	{
		if(this.validRand() != Const.FLAG_SUCCESS)
		{
			return INPUT;
		}
				
		log.debug(user);
		if(StringUtils.isNotBlank(user.getEmail()))
		{
			user.setEmail(StringUtils.trim(user.getEmail()));
			User vo = this.userService.findUniqueBy("email", user.getEmail());
			if (vo == null)
			{
				user.setRegdate(new Date());
				user.setState(User.INVALID);
				user.setNickName(StringUtils.substringBefore(user.getEmail(), "@"));
				user.setLogo(SysConfig.get("defalut_head_pic"));
				
				this.userService.save(user);
				
				this.sendActivateInfo(user);
				this.setUserToSession(user);
				return MSGINFO;
			}
			else
			{
				this.getRequest().setAttribute(Const.KEY_INFO_MSG, "此邮箱已经注册!");
				
				return INPUT;
			}
		}
		else
		{
			this.getRequest().setAttribute(Const.KEY_INFO_MSG, "邮箱非法，请确认！");
			return INPUT;
		}
	}

	/**
	 * 转向取激活码页面。
	 * @return
	 */
	public String gotoActivate()
	{
		return "getActivateInfo";
	}
	
	/**
	 * 激活
	 */
	public String activate()
	{
		if(log.isDebugEnabled())
		{
			log.debug("uid=" + uid);
			log.debug("key=" + key);
		}		
		
		if(uid == 0 || StringUtils.isBlank(key))
		{
			this.getRequest().setAttribute(Const.KEY_INFO_MSG,
					"非法的激活码!");
			log.error("uid=" + uid);
			log.error("key=" + key);
			return INFO;
		}
		
		User user = this.userService.get(uid);
		
		if(user == null)
		{
			this.getRequest().setAttribute(Const.KEY_INFO_MSG,
					"非法的激活码!");
			log.error("uid=" + uid);
			log.error("key=" + key);
			return INFO;
		}
		
		if(user.getState() == User.VALID)
		{
			this.getRequest().setAttribute(Const.KEY_INFO_MSG,
					"此邮箱已激活过！");
			return INFO;
		}
		else if(user.getState() == User.TEMP)
		{
			this.getRequest().setAttribute(Const.KEY_INFO_MSG,
			        "Sorry，临时用户不能被激活!");
			return INFO;
		}
		
		if ( key.equals(com.ambow.core.util.MD5.crypt(Const.MD5_PREFIX + user.getEmail())))
		{
			user.setState(User.VALID);
			this.userService.save(user);
			this.setUserToSession(user);
			return "modifyUserInfo";
		}
		else
		{
			this.getRequest().setAttribute(Const.KEY_INFO_MSG,
			        "非法的激活码!");
			return INFO;
		}
	}
	
	/**
	 * 取激活码
	 * @return
	 */
	public String getActivateInfo()
	{
		log.debug(user);
		if(this.validRand() != Const.FLAG_SUCCESS)
		{
			return "getActivateInfo";
		}
		
		if(StringUtils.isNotBlank(user.getEmail()))
		{
			User vo = this.userService.findUniqueBy("email", user.getEmail());
			if (vo != null )
			{			
				this.sendActivateInfo(vo);
				return INFO;
			}
			else
			{
				this.getRequest().setAttribute(Const.KEY_INFO_MSG, "尊敬的用户，此邮箱["+ user.getEmail() +"]未注册！ <a href='"+ this.getUrlPath() +"/user/reg.do'>现在去注册</a>");
				return "getActivateInfo";
			}
		}
		else
		{
			this.getRequest().setAttribute(Const.KEY_INFO_MSG, "尊敬的用户，此邮箱["+ user.getEmail() +"]不合法！");
			return "getActivateInfo";
		}
	}
	
	/**
	 * 发送注册的激活邮件
	 * @param user
	 */
	private void sendActivateInfo(User user)
	{

		if ( user == null )
		{
			log.error("user is null!");
			return;
		}
		String activeUrl =  this.getUrlPath() + "/user/regAction!activate.do?uid="+user.getId()
		        +"&key=" + com.ambow.core.util.MD5.crypt(Const.MD5_PREFIX + user.getEmail());
		if(log.isDebugEnabled())
		{
			log.debug("activeUrl=" + activeUrl);
		}
		
		
		Map<String, Object> emailParam = new HashMap<String, Object>();
		emailParam.put("activeUrl", activeUrl);
		
		mailSendService.sendTemplateMail(Const.TEMPLATE_REGIESTER,user.getEmail(), emailParam);
		
		this.getRequest().setAttribute(Const.KEY_INFO_MSG,
				"激活码发送成功，请稍候去您的邮箱[" + user.getEmail() + "]中确认，谢谢！");
	}
	
	/**
	 * 修改密码
	 */
	public String modifyPassword()
	{
		String oldPassword = this.getRequest().getParameter("oldPassword");
		String newPassword = this.getRequest().getParameter("newPassword");
		
		user = this.getUserFromSession();
		
		if(user.getPassword().equals(oldPassword))
		{
			user.setPassword(newPassword);
			this.userService.save(user);
			this.setUserToSession(user);
		}
		else
		{
			this.getRequest().setAttribute(Const.KEY_INFO_MSG,
	        	"旧密码错误！");
			return "modifyPassword";
		}
		return HOME;
	}

	
	/**
	 * 修改资料
	 */
	public String modifyUserInfo()
	{
		User tmp = this.getUserFromSession();
		tmp.setNickName(user.getNickName());
		tmp.setDsc(user.getDsc());
		tmp.setBirthday(user.getBirthday());
		tmp.setMsn(user.getMsn());
		tmp.setGtalk(user.getGtalk());
		tmp.setMobile(user.getMobile());
		
		this.userService.save(tmp);
		this.setUserToSession(tmp);
		return HOME;
	
	}
	
	
	/**
	 * 转向取密码页面。
	 * @return
	 */
	public String gotoPassword()
	{
		return "getPassword";
	}
	
	/**
	 * 找回密码
	 */
	public String getPassword()
	{
		log.debug(user);
		if(this.validRand() != Const.FLAG_SUCCESS)
		{
			return "getPassword";
		}
		
		if(StringUtils.isNotBlank(user.getEmail()))
		{
			User vo = this.userService.findUniqueBy("email", user.getEmail());
			if (vo != null )
			{			
				Map<String, Object> emailParam = new HashMap<String, Object>();
				emailParam.put("password", user.getPassword());			
				mailSendService.sendTemplateMail(Const.TEMPLATE_GET_PASSWORD, user.getEmail(), emailParam);			
				
				this.getRequest().setAttribute(Const.KEY_INFO_MSG, "尊敬的用户，请到您的邮箱["+ user.getEmail() +"]中获取密码！");

				return INFO;
			}
			else
			{
				this.getRequest().setAttribute(Const.KEY_INFO_MSG, "尊敬的用户，此邮箱["+ user.getEmail() +"]未注册！ <a href='"+ this.getUrlPath() +"/user/reg.do'>现在去注册</a>");
				return "getPassword";
			}
		}
		else
		{
			this.getRequest().setAttribute(Const.KEY_INFO_MSG, "尊敬的用户，此邮箱["+ user.getEmail() +"]不合法！");
			return "getPassword";
		}
		
	}
	

	/**
	 * 验证随机数，主要给DWR调用
	 */
	public MessageInfo validRand2(String rand)
	{
		log.debug(rand);
		MessageInfo msg = null;
		if ( StringUtils.isNotBlank(rand))
		{
			HttpSession session = WebContextFactory.get().getSession(); 
			String sRand = (String)session.getAttribute("rand");
			if(sRand == null || !sRand.equals(rand))
			{
				msg = new MessageInfo(MessageCode.REG_NO_INVATE, SysConfig.get(MessageCode.REG_RAND_ERROR));
			}
			else
			{
				msg = new MessageInfo(MessageCode.SUCCESS);
			}
		}
		else
		{
			msg = new MessageInfo(MessageCode.REG_NO_INVATE, SysConfig.get(MessageCode.REG_RAND_ERROR));
		}
		log.debug(msg);
		return msg;
	}
	
	/**
	 * 验证注册邮箱，主要给DWR调用
	 */
	public MessageInfo validEmail(String semail)
	{
		log.debug(semail);
		MessageInfo msg = null;
		String tmp = StringUtils.trimToNull(semail);
		
		if(null != tmp && RegexUtils.isEmail(tmp))
		{			
			User vo = this.userService.findUniqueBy("email", tmp);
			if (vo == null)
			{
				msg = new MessageInfo(MessageCode.SUCCESS);
			}
			else if(vo.getState() == User.VALID)
			{
				msg = new MessageInfo(MessageCode.REG_IS_EXIST, SysConfig.get(MessageCode.REG_IS_EXIST));
			}
			else if(vo.getState() == User.INVALID)
			{
				msg = new MessageInfo(MessageCode.REG_NO_INVATE, SysConfig.get(MessageCode.REG_NO_INVATE));
			}
			else
			{
				msg = new MessageInfo(MessageCode.REG_STATE_INVALID, SysConfig.get(MessageCode.REG_STATE_INVALID));
			}
			
		}
		else
		{
			msg = new MessageInfo(MessageCode.REG_EMAIL_INVALID, SysConfig.get(MessageCode.REG_EMAIL_INVALID));
		}
		log.debug(msg);
		return msg;
	}
	


	public String getKey() {
		return key;
	}

	public void setKey(String key) {
		this.key = key;
	}

	public int getUid() {
		return uid;
	}

	public void setUid(int uid) {
		this.uid = uid;
	}

	public User getUser() {
		return user;
	}

	public void setUser(User user) {
		this.user = user;
	}

		
}
